package com.weizhi.business.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.ResponseDto;
import com.weizhi.server.entity.Chapter;
import com.weizhi.server.service.ChapterService;
import com.weizhi.server.util.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("admin/chapter")
public class ChapterController {

    private final static Logger logger = LoggerFactory.getLogger(ChapterController.class);

    @Autowired
    private ChapterService chapterService;

    @RequestMapping("list")
    public ResponseDto list(HttpServletRequest req) {
        JSONObject param = JsonUtil.convertRequest(req);
        logger.info("chapterController-list, param={}", param);
        if(StringUtils.isBlank(param.getString("courseId"))) throw new RuntimeException("请求参数异常");
        PageInfo pageInfo = chapterService.list(param);
        return ResponseDto.createBySuccess(pageInfo);
    }
    @RequestMapping("save")
    public ResponseDto save(@RequestBody Chapter chapter) {
        logger.info("chapterController-save, chapter={}", chapter);
        /*
            前端进行参数校验：减少无用请求占用服务器资源
            后端进行参数校验：防止用户使用非浏览器进行访问，没有进行参数校验
            后端参数校验失败时不返回具体信息，因为后端校验失败说明是前端校验出bug或者是非浏览器访问
         */

        if(StringUtils.isBlank(chapter.getName()) || chapter.getCourseId() == null)
            throw new RuntimeException("请求参数异常");
        chapterService.save(chapter);
        return ResponseDto.createBySuccess();
    }

    @DeleteMapping("/delete/{id}")
    public ResponseDto delete(@PathVariable Long id) {
        logger.info("chapterController-delete, id={}", id);
        chapterService.delete(id);
        return ResponseDto.createBySuccess();
    }
}

